package org.ben.birthday.twentybirthday.utils;

import org.ben.birthday.twentybirthday.dao.UserDaoRepository;
import org.ben.birthday.twentybirthday.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: Ben
 * @Date: 2019/7/23 9:41
 */
@Service
public class EmailSendServiceImpl implements IEmailSendService {

    /**
     * 邮箱发送类注入
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 用户Dao注入
     */
    @Autowired
    private UserDaoRepository userDaoRepository;

    private static final Logger logger = LoggerFactory.getLogger(EmailSendServiceImpl.class);

    /**
     * 邮箱发送Service
     * @param httpSession
     * @param email
     * @param string
     * @param chineseString
     */
    @Override
    public void sendEmailService(HttpSession httpSession, String email,String string,String chineseString) {
        SimpleMailMessage mainMessage = new SimpleMailMessage();
        RandomNumberUtils randomNumberUtils = new RandomNumberUtils();
        String verificationCode = randomNumberUtils.getRandonString(6);
        httpSession.setMaxInactiveInterval(60 * 2);
        httpSession.setAttribute(string+"verificationCode", verificationCode);
        logger.info(verificationCode);
        httpSession.setAttribute("email", email);
        //发送者
        mainMessage.setFrom("xxswhy109@163.com");
        //接收者
        mainMessage.setTo(email);
        //发送的标题
        mainMessage.setSubject("旅游管理系统"+chineseString+"验证码");
        //发送的内容
        mainMessage.setText("验证码：" + verificationCode + "您正在进行"+chineseString+"，请输入您的验证码继续完成操作。");
        mailSender.send(mainMessage);
    }

    /**
     * 邮箱注册查询Service
     * @param email
     * @return boolean
     */
    @Override
    public boolean registSelectEmailService(String email) {
        List<User> userList=userDaoRepository.findUsersByEmail(email);
        Iterator<User> userIterator=userList.iterator();
        while(userIterator.hasNext()){
            User user=userIterator.next();
            logger.error("该邮箱已被注册，请重新输入");
                return false;
        }
        logger.info("该邮箱未被注册，可以注册");
        return true;
    }

    /**
     * 邮箱登录查询Service
     * @param email
     * @return boolean
     */
    @Override
    public boolean loginSelectEmailService(String email) {
        List<User> userList=userDaoRepository.findUsersByEmail(email);
        Iterator<User> userIterator=userList.iterator();
        while(userIterator.hasNext()){
         logger.info("该邮箱存在，可以登录");
        return true;
        }
        logger.error("该邮箱未注册,无法登录");
       return false;
    }
}
